<template>
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名:" prop="">
                <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item label="" prop="">
                <el-button type="primary" @click="search" :disabled="keyword ? false : true">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button type="primary" @click="deleteSelectuser"
            :disabled="selectIdArr.length ? false : true">批量删除</el-button>
        <el-table border style="margin: 10px 0;" :data="userArr" @selection-change="selectChange">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="#" align="center" type="index"></el-table-column>
            <el-table-column label="id" align="center" prop="id"></el-table-column>
            <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名称" align="center" prop="name" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row, $index }">
                    <el-button type="primary" @click="setRole(row)" icon="User" size="small">分配角色</el-button>
                    <el-button type="primary" @click="updateUser(row)" icon="Edit" size="small">编辑</el-button>
                    <el-popconfirm :title="`你确定要删除${row.username}吗？`" width="250px" @confirm="deleteUser(row.id)">
                        <template #reference>
                            <el-button type="primary" @click="" icon="Delete" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
            :background="true" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
            @current-change="getHasUser" @size-change="handler" />
    </el-card>
    <!-- 添加和更新 -->
    <el-drawer v-model="drawer2">
        <template #header>
            <h4>{{ userParams.id ? "更新用户" : '添加用户' }}</h4>
        </template>
        <template #default>
            <el-form :model="userParams" :rules="rules" ref="formRef">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请您输入用户姓名" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请您输入用户昵称" v-model="userParams.name"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                    <el-input placeholder="请您输入用户密码" type="password" v-model="userParams.password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex:auto">
                <el-button type="primary" @click="cancel"> 取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </div>
        </template>
    </el-drawer>
    <!-- 分配角色 -->
    <el-drawer v-model="drawer3">
        <template #header>
            <h4>分配角色</h4>
        </template>
        <template #default>
            <el-form>
                <el-form-item label="用户姓名" prop="">
                    <el-input placeholder="" v-model="userParams.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="职位列表" prop="">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handlerCheckAllChange">
                        全选
                    </el-checkbox>
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">
                            {{ role.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex:auto">
                <el-button type="" @click="drawer3 = false">取消</el-button>
                <el-button type="primary" @click="confirm">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang='ts' name="User">
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqAllUser, reqAddUserOrUpdateUser, reqAllRole, reqSetRole, reqRemoveUser, reqRemoveAllUser } from '@/api/acl/user/index'
import type { UserResponseData, Records, RoleResponseData, allRolesList, assignRoles, SetRoleData } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus';
import useLayOutSettingStore from '@/store/modules/setting';
let LayOutSettingStore = useLayOutSettingStore()
let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
let userArr = ref<Records[]>([])
let drawer2 = ref<boolean>(false)
let drawer3 = ref<boolean>(false)
let formRef = ref<any>()
//复选框代码
let checkAll = ref<boolean>(false)
let isIndeterminate = ref<boolean>(true)
//存储全部职位数据
let allRole = ref<allRolesList>([])
//当前已有的职位
let userRole = ref<assignRoles>([])
//用来存储批量删除的用户的id
let selectIdArr = ref<any>([])
//搜索用的关键字
let keyword = ref<string>('')
const handlerCheckAllChange = (val: boolean) => {
    //val:true(全选)|false(没有全选)
    userRole.value = val ? allRole.value : []
    //不确定的样式
    isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
    checkAll.value = value.length === allRole.value.length
    isIndeterminate.value = value.length !== allRole.value.length
}
//收集用户信息的响应式数据
let userParams = reactive<Records>({
    username: '',
    name: '',
    password: ''
})
onMounted(() => {
    getHasUser()
})
const getHasUser = async (pager = 1) => {
    pageNo.value = pager
    let result: UserResponseData = await reqAllUser(pageNo.value, pageSize.value, keyword.value)
    if (result.code == 200) {
        total.value = result.data.total
        userArr.value = result.data.records
    }
}
const handler = (pageSizes: number) => {
    getHasUser()
}
//添加用户
const addUser = () => {
    drawer2.value = true
    Object.assign(userParams, {
        id: 0,
        username: '',
        name: '',
        password: ''
    })
    //清除上一次的错误提示信息
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
        formRef.value.clearValidate('password')
    })
}
//编辑
const updateUser = (row: Records) => {
    drawer2.value = true
    Object.assign(userParams, row)
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
    })
}
//抽屉组件的确定按钮
const save = async () => {
    // 点击按钮时，必须保证表单校验通过再去发请求
    await formRef.value.validate();
    let result: any = await reqAddUserOrUpdateUser(userParams)
    if (result.code == 200) {
        drawer2.value = false
        ElMessage({
            type: 'success',
            message: userParams.id ? '更新成功' : '添加成功'
        })
        // getHasUser(userParams.id ? pageNo.value : 1);
        //浏览器自动刷新一次
        window.location.reload()
    } else {
        ElMessage({ type: 'error', message: userParams.id ? '更新失败' : '添加失败' })
    }
}
//抽屉组件的取消按钮
const cancel = () => {
    drawer2.value = false
}
const validatorUserName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error('用户名字至少五位'))
    }
}
const validatorName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error('用户昵称至少五位'))
    }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 6) {
        callback()
    } else {
        callback(new Error('用户密码至少六位'))
    }
}
const rules = {
    username: [{ required: true, trigger: 'blur', validator: validatorUserName }],
    name: [{ required: true, trigger: 'blur', validator: validatorName }],
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }]
}
//分配角色按钮
const setRole = async (row: Records) => {

    Object.assign(userParams, row)
    //全部职位数据和当前用户已有的职位数据
    let result: RoleResponseData = await reqAllRole((userParams.id as number))
    if (result.code == 200) {
        allRole.value = result.data.allRolesList
        userRole.value = result.data.assignRoles
        drawer3.value = true
    }

}
//确定分配角色按钮
const confirm = async () => {
    let data: SetRoleData = {
        userId: (userParams.id as number),
        roleIdList: userRole.value.map(item => item.id)
    }
    let result: any = await reqSetRole(data)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '分配职务成功' })
        drawer3.value = false
        getHasUser(pageNo.value)
    }
}
//删除某一个用户
const deleteUser = async (userId: number) => {
    let result: any = await reqRemoveUser(userId)
    if (result == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}
//table复选框勾选
const selectChange = (val: any) => {
    selectIdArr.value = val

}
//批量删除
const deleteSelectuser = async () => {
    let idList: any = selectIdArr.value.map((item: any) => {
        return item.id
    })
    let result: any = await reqRemoveAllUser(idList)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}
//搜索
const search = () => {
    getHasUser()
    keyword.value = ''
}
//重置
const reset = () => {
    LayOutSettingStore.refsh = !LayOutSettingStore.refsh
}
</script>

<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>